<?php


namespace App\Models\Tool;


use Illuminate\Support\Facades\File;
use function Webmozart\Assert\Tests\StaticAnalysis\false;

/**创建添加魔板页面
 * Class MakeAddHtml
 * @package App\Models\Tool
 */
class MakeListHtmlAndJs
{

    static private $js_list_row = [];

    static private $js_list_button_top = '';
    static private $js_list_button_rigth = '';
    static private $js_list_button_row = '';
    static private $js_list_sort = '';

    static private $js_list_so = [];
    static private $html_list_so = [];
    static private $html_list_button_top = [];
    static private $html_list_button_rigth = [];
    static private $html_list_button_row = [];
    static private $istotalRow = false;
    static private $isSo = false;
    static private $isSoisshow = false;
    static private $isSort = false;
    static private $inputdata = [];



    static function make($html_file,$html_filename,$js_file,$js_filename,$data,$inputdata){
        /*
                [
        fied: "id"
        order: 0
        so: 0
        title: "id"
        total: 0
          ]*/
        self::$inputdata = $inputdata;
        self::$isSoisshow = $inputdata['buttons_show_so'];
        $iswith=count($data)>7?1:0;
        $isi=0;
        //列表字段
        foreach ($data as $data1){
            $sort=$data1['order']?'true':'false';
            $totalRow=$data1['total']?'true':'false';
            $isi++;
            $iswith=count($data)==$isi?1:0;
            self::$js_list_row[] = self::list_row_fixed($data1,$iswith);
            //是否有排序
            if($sort){
                self::$isSort=true;
            }
            //是否启用合计

            if($totalRow=='true'){
                self::$istotalRow=true;
            }
            if($data1['so']){
                self::$isSo = true;
                $formdata= self::form_so_line($data1);
                if($formdata['html'])self::$html_list_so[] = $formdata['html'];
            }

        }
        //头部搜索合并
        $form_so_row = self::form_so_row();
        self::$html_list_so = $form_so_row['html'];
        self::$js_list_so= $form_so_row['js'];
        //列表头部按钮
        $button_top = self::button_top();
        self::$html_list_button_top = $button_top['html'];
        self::$js_list_button_top= $button_top['js'];
        //列表右边按钮
        self::$js_list_button_rigth = self::button_rigth()['js'];
        //列表行按钮
        $row = self::button_row();
        self::$html_list_button_row = $row['html'];
        self::$js_list_button_row = $row['js'];

        if($row['js']!=''){
            $width = count($inputdata['buttons_row']) * 46;
            self::$js_list_row[] = "{fixed: 'right', width: $width, align:'center',title:'操作', toolbar: '#layui-data-table-barRow'}";
        }

        //排序
        self::$js_list_sort = self::button_sort()['js'];



        self::make_html($html_file,$js_file);
        self::make_js($js_file,$js_filename);

    }

    /**
     * 字段显示
     */
    private static function list_row_fixed($data1,$iswith){
        $sort=$data1['order'];
        $totalRow=$data1['total'];
        $fied=str_replace('.','_',$data1['fied']);

        $row = [];
        $row[]="field:'{$fied}'";
        $row[]="title: '{$data1['title']}'";
        if($data1['order']){
            $row[]="sort:true";
        }
        if($data1['total']){
            $row[]="totalRow:true";
        }
        if($iswith){
            $width = strlen($data1['title']) * 10;
            $width = $width < 50 ? 50 : $width;
            if($sort) $width += 10;
            $row[]="minWidth:{$width}";
        }
//list_type_status
        if($data1['list_type']=='image'){
            $link="\''+res.{$fied}+'\'";
            $row[]=<<<text
templet: function(res){
            if(!res.{$fied})return '';
            return '<img src="'+res.{$fied}+'" width="50" height="50" onclick="lookImage($link)" alt="">';
        }
text;
        }
        if($data1['list_type']=='link_opend' && $data1['list_type_status']!=''){
            $link="\'{$data1['list_type_status']}'+res.{$fied}+'\'";
            $row[]=<<<text
templet: function(res){
            return '<span  style="color: blue; cursor:pointer" onclick="openLink($link)" alt="">'+res.{$fied}+'</span>';
        }
text;

        }

        if($data1['list_type']=='timedate'){
            $row[]=<<<text
templet: function(res){
            return date('Y-m-d H:i:s',res.{$fied});
        }
text;
        }
        if($data1['list_type']=='type'  && $data1['list_type_status']!=''){
            $data1['list_type_status'] = str_replace('，', ',', $data1['list_type_status']);
            $list_type_status_arr = explode(',', $data1['list_type_status']);
            $list_type_status_row = [];
            $colors = [
                'red','#349706','#FD6605','#FC3204','#9C0163','#FF16A2','#000000','#c0c0c0','#2440C4'
                ,'red','#349706','#FD6605','#FC3204','#9C0163','#FF16A2','#000000','#c0c0c0','#2440C4'
                ,'red','#349706','#FD6605','#FC3204','#9C0163','#FF16A2','#000000','#c0c0c0','#2440C4'
            ];
            $idd=0;
            foreach ($list_type_status_arr as $list_type_status_arr1){
                $list_type_status_arr12=explode('=',$list_type_status_arr1);
                if(count($list_type_status_arr12)==2){
                    $list_type_status_arr1='<span style="color:'.$colors[$idd].'">'.$list_type_status_arr12[1].'</span>';
                    $list_type_status_row[] ="'{$list_type_status_arr12[0]}':'{$list_type_status_arr1}'" ;
                    $idd++;
                }

            }

            $list_type_status_row = '{'.join(',', $list_type_status_row).'};';
            $row[]=<<<text
templet: function(res){
            var Tp=$list_type_status_row
            var keyi=res.{$fied}.toString();
            if(Tp[keyi]){
                 return Tp[keyi];
            }
            return res.{$fied};
        }
text;
        }
        return "{".join(',',$row)."}";
    }

    private static function button_sort(){
        $html = '';
        $js = '';
        if(self::$isSort){
            $js = <<<text
 table.on('sort('+table_elem_id+')', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        console.log(obj.field); //当前排序的字段名
        console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
        console.log(this) //当前排序的 th 对象*/

        return false;
    });
text;
        }




        return ['html'=>$html,'js'=>$js];
    }
    private static function button_rigth(){
        $toolbar_buttons = [];
        if(isset(self::$inputdata['buttons_rigth']) && count(self::$inputdata['buttons_rigth'])>0){
            $toolbar_buttons_js = ["'".join("','",self::$inputdata['buttons_rigth'])."'"];
        }else{ $toolbar_buttons_js = [''];}

        if(self::$isSo){
            $toolbar_buttons_js[]=<<<text
{ //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
          title: '提示'
          ,layEvent: 'ShowSearch'
          ,icon: 'layui-icon-search'
        }
text;

        }


        $js = '';

        $html = join("\n", $toolbar_buttons);
        if(count($toolbar_buttons_js)>0){
            $js =join(",", $toolbar_buttons_js);
            $js = ",defaultToolbar: [$js]";
        }

        return ['html'=>$html,'js'=>$js];
    }
    private static function button_row(){
        $toolbar_buttons = [];
        $toolbar_buttons_js = [];
        if(in_array('edit',self::$inputdata['buttons_row'])){
            $toolbar_buttons[]='<a class="layui-btn layui-btn-primary layui-btn-xs layui-border-green" lay-event="edit"><i class="layui-icon layui-icon-edit"></i></a>';
            $toolbar_buttons_js[]=<<<text

    var edit=function(id){
     layer.open({
                type: 2
                ,title: '修改'
                ,content: './edit?id='+id
                ,maxmin: true
                ,area: ['420px', '620px']
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'LAY-user-role-submit'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    //监听提交
                    iframeWindow.layui.form.on('submit('+submitID+')', function(data){
                        var field = data.field; //获取提交的字段

                        //提交 Ajax 成功后，静态更新表格中的数据
                        $.ajax({
                            url:'./edit',
                            type:'POST',
                            data:field,
                            success:function(result){
                                layer.msg(result.message)
                                if(result.code==200){
                                    table.reload(table_elem_id); //数据刷新
                                    layer.close(index); //关闭弹层
                                }

                            }});

                    });

                    submit.trigger('click');
                }
            });
    };


text;

        }
        if(in_array('dele',self::$inputdata['buttons_row'])){
            $toolbar_buttons[]='<a class="layui-btn layui-btn-primary layui-btn-xs layui-border-red" lay-event="del"><i class="layui-icon layui-icon-delete"></i></a>';
            $toolbar_buttons_js[]=<<<text
 var deleFuc=function(ids){
            layer.confirm('确定删除吗？', function(index) {
                //执行 Ajax 后重载
                $.ajax({
                    url:'./dele',
                    type:'POST',
                    data:{ids:ids},
                    success:function(result){
                        layer.close(index);
                        layer.msg(result.message)
                        if(result.code==200){
                            table.reload(table_elem_id);
                        }

                    }});

            });
        }
text;
        }
        if(in_array('info',self::$inputdata['buttons_row'])){
            $toolbar_buttons[]='<a class="layui-btn layui-btn-primary layui-btn-xs layui-border-blue" lay-event="info"><i class="layui-icon layui-icon-right"></i></a>';
            $toolbar_buttons_js[]=<<<text
 var infoFuc=function(id){
     layer.open({
                type: 2
                ,title: '详情'
                ,content: './info?id='+id
                ,maxmin: true
                ,area: ['100%', '100%']
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    layer.close(index); //关闭弹层
                }
            });
    };
text;
        }

        if(count($toolbar_buttons_js)>0 ){
            $toolbar_buttons_js[]=<<<text
        //监听行工具事件
    table.on('tool('+table_elem_id+')', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值

        if(layEvent === 'info'){
           infoFuc(data.id);
        } else if(layEvent === 'del'){
            deleFuc(data.id);
        }else if(layEvent === 'edit'){
            edit(data.id);
        }
    });
text;

        }



        $html = join("\n", $toolbar_buttons);

        $js =join("\n", $toolbar_buttons_js);
        return ['html'=>$html,'js'=>$js];
    }
    private static function button_top(){
        $top_buttons = [];
        $top_buttons_js = [];
        if(in_array('pldele',self::$inputdata['buttons_top'])){
            $top_buttons[]='<button class="layui-btn layui-btn-sm layui-btn-danger layuiadmin-btn-list " lay-event="delAll"><i class="layui-icon layui-icon-delete"></i>批量删除</button>';
        }
        if(in_array('add',self::$inputdata['buttons_top'])){
            $top_buttons[]='<button class="layui-btn layui-btn-sm layuiadmin-btn-list" lay-event="add"><i class="layui-icon"></i>新增</button>';
            $top_buttons_js[]=<<<text
var add=function(){
     layer.open({
                type: 2
                ,title: '新增'
                ,content: './add'
                ,area: ['420px', '620px']
                ,maxmin: true
                ,btn: ['确定', '取消']
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'LAY-user-role-submit'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    //监听提交
                    iframeWindow.layui.form.on('submit('+submitID+')', function(data){
                        var field = data.field; //获取提交的字段

                        //提交 Ajax 成功后，静态更新表格中的数据
                        $.ajax({
                            url:'./add',
                            type:'POST',
                            data:field,
                            success:function(result){
                                layer.msg(result.message)
                                if(result.code==200){
                                    table.reload(table_elem_id); //数据刷新
                                    layer.close(index); //关闭弹层
                                }

                            }});

                    });

                    submit.trigger('click');
                }
            });
    };
text;

        }

        $html = join("\n", $top_buttons);

        $js = join("\n", $top_buttons_js);
        return ['html'=>$html,'js'=>$js];
    }
    private static function form_so_line($data1){
        //关联表替换成 as 后的字段名
        $data1['fied']=str_replace('.', '_', $data1['fied']);
        $html=<<<text
        <div class="layui-inline">
            <label class="layui-form-label">{$data1['title']}</label>
            <div class="layui-input-inline">
              <input type="text" name="{$data1['fied']}" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
text;

        $js = '';
        return ['html'=>$html,'js'=>$js];
    }
    private static function form_so_row(){
        $isshow=self::$isSoisshow?'':'display: none';
        $html = '';
        $js = '';
        if(self::$isSo){
            $middhtml = join("\n", self::$html_list_so);
            $html=<<<text
<div id="searchBox" style="{$isshow}" class="layui-form  layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">


          {$middhtml}

          <!--<div class="layui-inline">
            <label class="layui-form-label">文章标签</label>
            <div class="layui-input-inline">
              <select name="label">
                <option value="">请选择标签</option>
                <option value="0">美食</option>
                <option value="1">新闻</option>
                <option value="2">八卦</option>
                <option value="3">体育</option>
                <option value="4">音乐</option>
              </select>
            </div>
          </div>-->

          <div class="layui-inline">
            <button class="layui-btn layuiadmin-btn-list" lay-submit lay-filter="LAY-app-contlist-search">
              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
            </button>
          </div>
        </div>
      </div>
text;


            $js=<<<text
//监听搜索
    form.on('submit(LAY-app-contlist-search)', function(data){
      var field = data.field;

      //执行表格数据重载
      table.reload(table_elem_id, {
        where: field
      });
    });
text;


        }


        return ['html'=>$html,'js'=>$js];
    }
    /**生成html
     * @param $html_file
     * @param $html_filename
     * @param $js_file
     * @param $middhtml
     */
    private static function make_html($html_file,$js_file){
        $js_file=str_replace('\\','/',$js_file).'?'.date('Y_m_d_H_i_s');




        $html_list_so = self::$html_list_so;
        $top_buttons = self::$html_list_button_top;
        $toolbar_buttons = self::$html_list_button_row;
        $inputp = self::$inputdata;

        $makecontent=<<<text
@extends('admin.defaults.head')
@section('title','{$inputp["controllername"]}')
@section('body')

{{--请在下面编辑body 内容--}}


  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-card">


           {$html_list_so}

          <div class="layui-card-body">
            <table class="layui-hide" id="layui-data-table" lay-filter="layui-data-table"></table>
            <script type="text/html" id="layui-data-table-toolbar">
              <div class="layui-btn-container">
                 {$top_buttons}
              </div>
            </script>
            <script type="text/html" id="layui-data-table-barRow">
                <div class="layui-btn-group1">
                {$toolbar_buttons}
</div>

            </script>
          </div>
        </div>
      </div>
    </div>
  </div>

{{--上方body内容结束   请在下面编辑script 内容--}}

@endsection
@section('script')
<script src="/{$js_file}"></script>
@endsection
text;
        $html_file=resource_path($html_file);
        // 写入文件，存在的话覆盖写入
        File::replace(($html_file), $makecontent);
    }

    /**生成js
     * @param $js_file
     * @param $js_filename
     * @param $middjs
     */
    private static function make_js($js_file,$js_filename){
        $middrowjs = join("\n        ,", self::$js_list_row);
        $js_file=public_path($js_file);

        $istotalRow=self::$istotalRow?', totalRowText: \'合计\'':'';
        $istotalRow_rw = '';
        if(self::$istotalRow){
            $istotalRow_rw = ',totalRow:true';
        }
        $js_so=self::$js_list_so;
        $js_add=self::$js_list_button_top;
        $js_edit_dele_info_row=self::$js_list_button_row;
        $js_rigth=self::$js_list_button_rigth;
        $js_list_sort = self::$js_list_sort;

        $makecontent=<<<text


var $,table,form,table_elem_id;
layui.use(['table','form'], function(){
     $ = layui.$
     ,table = layui.table
     ,form = layui.form
     ,table_elem_id='layui-data-table';



    table.render({
      elem: '#'+table_elem_id
      ,url: './lists'
      ,parseData: function(res){ //res 即为原始返回的数据
        return {
          "code": res.code==200?0:res.code, //解析接口状态
          "msg": res.message, //解析提示文本
          "count": res.data.total, //解析数据长度
          "data": res.data.data //解析数据列表
        };
      }
       {$js_rigth}
      ,toolbar:'#layui-data-table-toolbar'
      ,height: 'full-100'
      ,cellMinWidth: 80
      {$istotalRow_rw}
      ,page: true
      ,limit: 15
      ,cols: [[
        {title: '序号',templet: '#indexTpl',type:'numbers', fixed: 'left' $istotalRow}
        ,{type:'checkbox', fixed: 'left' }
        ,{$middrowjs}

      ]]
    });


    {$js_so}
    {$js_add}
    {$js_edit_dele_info_row}






    //监听排序
    {$js_list_sort}




     //头工具栏事件
  table.on('toolbar('+table_elem_id+')', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
      case 'delAll':
         var checkStatus = table.checkStatus(table_elem_id)
        ,checkData = checkStatus.data; //得到选中的数据

        if(checkData.length === 0){
          return layer.msg('请选择数据');
        }
        var ids=[];
        for(var i in checkData){
            ids.push(checkData[i].id);
        }
        deleFuc(ids.join(','));
      break;
      case 'add':
        add();
      break;
      //自定义头工具栏右侧图标 - 提示
      case 'ShowSearch':
      var display=$("#searchBox").css('display');
       $("#searchBox").css('display',display=='block'?'none':'block');
      break;
    };
  });





})
text;

        // 写入文件，存在的话覆盖写入
        File::replace($js_file, $makecontent);
    }





}
